package com.example.searchcenter.article;

import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.searchcenter.R;
import com.example.searchcenter.helper.AlertDialogManager;
import com.example.searchcenter.helper.ConnectionDetector;
import com.example.searchcenter.helper.JSONParser;



public class News extends Activity {
	
	ListView list_article;
	TextView ver;
	TextView name;
	TextView thumbnail;

	// Connection Detector
	ConnectionDetector cd;
	
	// Alert dialog manager
	AlertDialogManager alert = new AlertDialogManager();
	
	// Hashmap articlelist
	ArrayList<HashMap<String, String>> articlelist = new ArrayList<HashMap<String,String>>();
	
	// URL get Json
	private static String url = "http://tinhnguyen.edu.vn/apis/getAllArticle";
	
	// Json node name
	
	/*`id`, `date`, `title`, `categoryid`, `titleASCII`, `authorId`, `tag`, `sumary`, `details`,
    `source`, `relativePlaceId`, `status`, `like`, `dislike`, `thumbnailImageUrl`,
    `view`, `FBShare`, `GPlusShare`, `tags`, `storyid`*/
	
	public static final String TAG_ARTICLES = "article";
	public static final String TAG_ID_ARTICLE = "cid";
	public static final String TAG_DATE = "date";
	public static final String TAG_TITLE = "title";
	public static final String TAG_CATEGORYID = "categoryid";
	public static final String TAG_TITLEASCII = "titleASCII";
	public static final String TAG_AUTHORID = "authorId";
	public static final String TAG_TAG = "tag";
	public static final String TAG_SUMARY = "sumary";
	public static final String TAG_DETAILS = "details";
	public static final String TAG_SOURCE = "source";
	public static final String TAG_THUMBNAILIMAGEURL = "thumbnailImageUrl";
	
	JSONArray arrArticle = null;
	NewsAdapter articleadapter;
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        cd = new ConnectionDetector(getApplication());
        
     // Check for internet connection
		if (!cd.isConnectingToInternet()) {
			// Internet Connection is not present
			alert.showAlertDialog(News.this, "Internet Connection Error",
					"Please connect to working Internet connection", false);
			// stop executing code by return
			News.this.finish();
		}
        
        setContentView(R.layout.news);
        articlelist = new ArrayList<HashMap<String,String>>();
        new JSONParse().execute();
    }
        private class JSONParse extends AsyncTask<String, String, JSONObject> {
        	private ProgressDialog pDialog;

    		@Override
    		protected void onPreExecute() {
    			super.onPreExecute();

    			pDialog = new ProgressDialog(News.this);
    			pDialog.setMessage("Getting Data ...");
    			pDialog.setIndeterminate(false);
    			pDialog.setCancelable(true);
    			pDialog.show();
    		}

    		@Override
    		protected JSONObject doInBackground(String... args) {
    			JSONParser jParser = new JSONParser();
    			// Getting JSON from URL
    			JSONObject json = jParser.getJSONFromUrl(url);
    			//Toast.makeText(getApplicationContext(),json.toString(), Toast.LENGTH_LONG).show();
    			return json;
    		}
    		
    		/*`id`, `date`, `title`, `categoryid`, `titleASCII`, `authorId`, `tag`, `sumary`, `details`,
    	    `source`, `relativePlaceId`, `status`, `like`, `dislike`, `thumbnailImageUrl`,
    	    `view`, `FBShare`, `GPlusShare`, `tags`, `storyid`*/
    		@Override
    		protected void onPostExecute(JSONObject json) {
    			pDialog.dismiss();
    			
    			try{
    				arrArticle = json.getJSONArray(TAG_ARTICLES);
    				
    				for(int i = 0; i < arrArticle.length(); i++)
    				{
    					JSONObject c = arrArticle.getJSONObject(i);
    					String cid = c.getString(TAG_ID_ARTICLE);
    					String date = c.getString(TAG_DATE);
    					String title = c.getString(TAG_TITLE);
    					String categoryid = c.getString(TAG_CATEGORYID);
    					String titleASCII = c.getString(TAG_TITLEASCII);
    					String authorId = c.getString(TAG_AUTHORID);
    					String tag = c.getString(TAG_TAG);
    					String sumary = c.getString(TAG_SUMARY);
    					String details = c.getString(TAG_DETAILS);
    					String source = c.getString(TAG_SOURCE);
    					String thumbnail = c.getString(TAG_THUMBNAILIMAGEURL);
    					
    					// Adding value HashMap key => value
    					HashMap<String, String> hash_article = new HashMap<String, String>();
    					hash_article.put(TAG_ID_ARTICLE, cid);
    					hash_article.put(TAG_DATE, date);
    					hash_article.put(TAG_TITLE, title);
    					hash_article.put(TAG_CATEGORYID, categoryid);
    					hash_article.put(TAG_TITLEASCII, titleASCII);
    					hash_article.put(TAG_AUTHORID, authorId);
    					hash_article.put(TAG_TAG, tag);
    					hash_article.put(TAG_SUMARY, sumary);
    					hash_article.put(TAG_DETAILS, details);
    					hash_article.put(TAG_SOURCE, source);
    					hash_article.put(TAG_THUMBNAILIMAGEURL, thumbnail);
    					
    					articlelist.add(hash_article);
    					
    					list_article = (ListView) findViewById(R.id.list_article);
    					
    					articleadapter = new NewsAdapter(News.this, articlelist);
    					
    					// Click go to detail article
    					list_article.setAdapter(articleadapter);
    					list_article.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    						
    						@Override
    						public void onItemClick(AdapterView<?> parent,
    								View view, int position, long id) {
    							// getting values from selected ListItem
    							String id_article = ((TextView) view
    									.findViewById(R.id.id_article))
    									.getText().toString();
    							
    							// Starting new intent
    							Intent in = new Intent(getApplicationContext(), DetailArticle.class );
    							
    							// sending pid to next activity
    							in.putExtra(TAG_ID_ARTICLE, id_article);
    							// starting new activity and expecting some response
    							// back
    							startActivityForResult(in, 100);
    							
    							/*Toast.makeText(
    									News.this,
    									"Bạn đã chọn  "
    											+ articlelist.get(+position).get(
    													"name") ,
    									Toast.LENGTH_SHORT).show();*/
    						}
						});
    					
    				}
    			}
    			catch(JSONException e){
    				e.printStackTrace();
    			}
    		}
        }
}

